package com.accp.dao.impl;

import com.accp.dao.ComputerDao;
import com.accp.pojo.Computer;
import org.hibernate.Query;


import java.util.List;


public class ComputerDaoImpl extends BaseDaoImpl implements ComputerDao{

    @SuppressWarnings("unchecked")
    @Override
    public List<Computer> selectByName(String className, String dname ) {
        Query query = this.getSession().createQuery("from "+ className );
        return query.list();
    }

    @Override
    public int delete(int id) {
        try {
            //获取对象的id
            Object d=this.getSession().get(Computer.class,id);
            //执行删除方法  删除id
            this.getSession().delete(d);
            //删除成功  return 1;
            return 0;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
        }
        return 1;

    }

    @Override
    public int  add(Computer computer) {
        try {
            //调用我们定义的接口  增加数据
            this.getSession().save(computer);
            return 1;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
        }
        return 0;
    }

    @Override
    public int  update(Computer computer) {
        try {
            //调用我们定义的接口  增加数据
            this.getSession().update(computer);
            return 1;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getStackTrace());
        }
        return 0;
    }

    @Override
    public Computer findById(Integer id) {
        Computer computer= (Computer) this.getSession().get(Computer.class, id);
        return computer;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Computer> selectByPage(String className, int pageNo, int pageSize) {
        Query query = this.getSession().createQuery("from "+ className);
        query.setFirstResult((pageNo - 1) * pageSize);//每页显示的第一条记录
        query.setMaxResults(pageSize);//每页显示的记录数
        return query.list();
    }

    @Override
    public int totalPage(String className) {
        String hql = "select count(*) from "+ className;
        Query query = this.getSession().createQuery(hql);
        int total = Integer.parseInt(query.list().get(0).toString());
        return total;
    }
}
